package com.example.familylibrary.service.impl;

import com.example.familylibrary.dto.UserDTO;
import com.example.familylibrary.entity.UserEntity;
import com.example.familylibrary.repository.UserRepository;
import com.example.familylibrary.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public UserDTO register(UserDTO userDTO) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(userDTO.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }

        // 创建用户实体
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername(userDTO.getUsername());
        userEntity.setPassword(passwordEncoder.encode(userDTO.getPassword()));
        userEntity.setNickname(userDTO.getNickname());
        userEntity.setEmail(userDTO.getEmail());
        userEntity.setPhone(userDTO.getPhone());
        userEntity.setAvatar(userDTO.getAvatar());
        userEntity.setStatus(userDTO.getStatus() != null ? userDTO.getStatus() : 1);

        // 保存用户
        UserEntity savedUser = userRepository.save(userEntity);

        // 转换为DTO并返回
        UserDTO result = new UserDTO();
        BeanUtils.copyProperties(savedUser, result);
        return result;
    }

    @Override
    public String login(String username, String password) {
        Optional<UserEntity> userOptional = userRepository.findByUsername(username);
        if (userOptional.isPresent()) {
            UserEntity user = userOptional.get();
            if (passwordEncoder.matches(password, user.getPassword())) {
                // 这里应该生成JWT token，简化处理直接返回成功信息
                return "登录成功";
            }
        }
        throw new RuntimeException("用户名或密码错误");
    }

    @Override
    public Optional<UserDTO> getUserById(Long id) {
        return userRepository.findById(id).map(userEntity -> {
            UserDTO userDTO = new UserDTO();
            BeanUtils.copyProperties(userEntity, userDTO);
            return userDTO;
        });
    }

    @Override
    public UserDTO updateUser(Long id, UserDTO userDTO) {
        UserEntity userEntity = userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 更新用户信息
        userEntity.setNickname(userDTO.getNickname());
        userEntity.setEmail(userDTO.getEmail());
        userEntity.setPhone(userDTO.getPhone());
        userEntity.setAvatar(userDTO.getAvatar());

        UserEntity updatedUser = userRepository.save(userEntity);

        UserDTO result = new UserDTO();
        BeanUtils.copyProperties(updatedUser, result);
        return result;
    }

    @Override
    public void updatePassword(Long id, String newPassword) {
        UserEntity userEntity = userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        userEntity.setPassword(passwordEncoder.encode(newPassword));
        userRepository.save(userEntity);
    }
}